<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Task;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class TaskController extends Controller
{
    public function index(Request $request)
    {
        $query = Auth::user()->tasks();

        if ($request->has('since')) {
            $since = $request->get('since');
            $query->where('last_modified_at', '>', $since)
                  ->orWhere('deleted_at', '>', $since);
        }

        $tasks = $query->withTrashed()->orderBy('sort_order')->get();

        return response()->json([
            'success' => true,
            'data' => $tasks,
            'timestamp' => now()->toISOString()
        ]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'list_id' => 'nullable|exists:todo_lists,id',
            'client_id' => 'required|string|unique:tasks,client_id',
            'title' => 'required|string|max:255',
            'text' => 'required|string',
            'description' => 'nullable|string',
            'priority' => 'in:low,medium,high',
            'status' => 'in:pending,in_progress,completed',
            'due_date' => 'nullable|date',
            'start_time' => 'nullable|date',
            'end_time' => 'nullable|date',
            'pomodoro_required' => 'integer|min:0',
            'repeat_type' => 'in:none,daily,weekly,monthly',
            'notes' => 'nullable|string'
        ]);

        $task = Auth::user()->tasks()->create(array_merge($validated, [
            'last_modified_at' => now()
        ]));

        return response()->json([
            'success' => true,
            'data' => $task
        ], 201);
    }

    public function update(Request $request, Task $task)
    {
        $this->authorize('update', $task);

        $validated = $request->validate([
            'list_id' => 'nullable|exists:todo_lists,id',
            'title' => 'string|max:255',
            'text' => 'string',
            'description' => 'nullable|string',
            'completed' => 'boolean',
            'priority' => 'in:low,medium,high',
            'status' => 'in:pending,in_progress,completed',
            'due_date' => 'nullable|date',
            'start_time' => 'nullable|date',
            'end_time' => 'nullable|date',
            'pomodoro_count' => 'integer|min:0',
            'pomodoro_completed' => 'integer|min:0',
            'pomodoro_required' => 'integer|min:0',
            'repeat_type' => 'in:none,daily,weekly,monthly',
            'notes' => 'nullable|string',
            'version' => 'integer|min:1'
        ]);

        // 递增版本号并更新修改时间
        $currentVersion = $task->version ?? 1;
        $newVersion = $currentVersion + 1;

        // 添加调试日志
        \Log::info('TaskController: 更新任务版本', [
            'task_id' => $task->id,
            'client_id' => $task->client_id,
            'title' => $task->title,
            'current_version' => $currentVersion,
            'new_version' => $newVersion,
            'updates' => array_keys($validated)
        ]);

        $task->update(array_merge($validated, [
            'version' => $newVersion,
            'last_modified_at' => now()
        ]));

        return response()->json([
            'success' => true,
            'data' => $task
        ]);
    }

    public function destroy(Task $task)
    {
        $this->authorize('delete', $task);

        $task->delete();

        return response()->json([
            'success' => true,
            'message' => '任务已删除'
        ]);
    }

    // 批量同步任务
    public function sync(Request $request)
    {
        $validated = $request->validate([
            'tasks' => 'required|array',
            'tasks.*.client_id' => 'required|string',
            'tasks.*.title' => 'required|string',
            'tasks.*.text' => 'required|string',
            'tasks.*.completed' => 'boolean',
            'tasks.*.deleted' => 'boolean',
            'tasks.*.version' => 'integer|min:1',
            'tasks.*.last_modified_at' => 'required|date',
            'tasks.*.list_id' => 'nullable|exists:todo_lists,id',
            'tasks.*.description' => 'nullable|string',
            'tasks.*.priority' => 'nullable|in:low,medium,high',
            'tasks.*.status' => 'nullable|in:pending,in_progress,completed',
            'tasks.*.due_date' => 'nullable|date',
            'tasks.*.start_time' => 'nullable|date',
            'tasks.*.end_time' => 'nullable|date',
            'tasks.*.pomodoro_required' => 'nullable|integer|min:0',
            'tasks.*.pomodoro_count' => 'nullable|integer|min:0',
            'tasks.*.pomodoro_completed' => 'nullable|integer|min:0',
            'tasks.*.repeat_type' => 'nullable|in:none,daily,weekly,monthly',
            'tasks.*.notes' => 'nullable|string'
        ]);

        $syncedTasks = [];

        foreach ($validated['tasks'] as $taskData) {
            // 查找任务，包括软删除的任务
            $task = Task::withTrashed()
                ->where('user_id', Auth::id())
                ->where('client_id', $taskData['client_id'])
                ->first();

            if ($task) {
                $serverVersion = $task->version ?? 1;
                $clientVersion = $taskData['version'] ?? 1;

                \Log::info('TaskController sync: 检查任务版本', [
                    'client_id' => $taskData['client_id'],
                    'title' => $taskData['title'],
                    'server_version' => $serverVersion,
                    'client_version' => $clientVersion,
                    'server_time' => $task->last_modified_at,
                    'client_time' => $taskData['last_modified_at']
                ]);

                // 如果服务器版本更新，返回服务器版本
                if ($task->last_modified_at > $taskData['last_modified_at']) {
                    $syncedTasks[] = $task;
                    continue;
                }

                if ($taskData['deleted'] ?? false) {
                    $task->delete();
                    \Log::info('TaskController sync: 删除任务', ['client_id' => $taskData['client_id']]);
                } else {
                    $task->restore();

                    // 递增版本号
                    $newVersion = max($serverVersion, $clientVersion) + 1;

                    $task->update(array_merge([
                        'title' => $taskData['title'],
                        'text' => $taskData['text'],
                        'completed' => $taskData['completed'] ?? false,
                        'priority' => $taskData['priority'] ?? 'medium',
                        'version' => $newVersion,
                        'last_modified_at' => now()
                    ], array_filter([
                        'list_id' => $taskData['list_id'] ?? null,
                        'description' => $taskData['description'] ?? null,
                        'status' => $taskData['status'] ?? null,
                        'due_date' => $taskData['due_date'] ?? null,
                        'start_time' => $taskData['start_time'] ?? null,
                        'end_time' => $taskData['end_time'] ?? null,
                        'pomodoro_required' => $taskData['pomodoro_required'] ?? null,
                        'pomodoro_count' => $taskData['pomodoro_count'] ?? null,
                        'pomodoro_completed' => $taskData['pomodoro_completed'] ?? null,
                        'repeat_type' => $taskData['repeat_type'] ?? null,
                        'notes' => $taskData['notes'] ?? null
                    ], function($value) { return $value !== null; })));

                    \Log::info('TaskController sync: 更新任务', [
                        'client_id' => $taskData['client_id'],
                        'new_version' => $newVersion
                    ]);
                }
            } else {
                // 任务不存在，只有在不是删除操作时才创建
                if (!($taskData['deleted'] ?? false)) {
                    // 再次检查是否存在软删除的任务（防止并发问题）
                    $existingTask = Task::withTrashed()
                        ->where('user_id', Auth::id())
                        ->where('client_id', $taskData['client_id'])
                        ->first();
                    
                    if ($existingTask) {
                        // 如果存在软删除的任务，恢复并更新
                        $existingTask->restore();
                        $newVersion = ($existingTask->version ?? 1) + 1;
                        
                        $existingTask->update(array_merge([
                             'title' => $taskData['title'],
                             'text' => $taskData['text'],
                             'completed' => $taskData['completed'] ?? false,
                             'priority' => $taskData['priority'] ?? 'medium',
                             'version' => $newVersion,
                             'last_modified_at' => now()
                         ], array_filter([
                             'list_id' => $taskData['list_id'] ?? null,
                             'description' => $taskData['description'] ?? null,
                             'status' => $taskData['status'] ?? null,
                             'due_date' => $taskData['due_date'] ?? null,
                             'start_time' => $taskData['start_time'] ?? null,
                             'end_time' => $taskData['end_time'] ?? null,
                             'pomodoro_required' => $taskData['pomodoro_required'] ?? null,
                             'pomodoro_count' => $taskData['pomodoro_count'] ?? null,
                             'pomodoro_completed' => $taskData['pomodoro_completed'] ?? null,
                             'repeat_type' => $taskData['repeat_type'] ?? null,
                             'notes' => $taskData['notes'] ?? null
                         ], function($value) { return $value !== null; })));
                        
                        $task = $existingTask;
                        \Log::info('TaskController sync: 恢复并更新软删除任务', [
                            'client_id' => $taskData['client_id'],
                            'new_version' => $newVersion
                        ]);
                    } else {
                        // 真正创建新任务，使用try-catch处理重复条目错误
                        try {
                            $task = Auth::user()->tasks()->create(array_merge([
                                'client_id' => $taskData['client_id'],
                                'title' => $taskData['title'],
                                'text' => $taskData['text'],
                                'completed' => $taskData['completed'] ?? false,
                                'priority' => $taskData['priority'] ?? 'medium',
                                'version' => $taskData['version'] ?? 1,
                                'last_modified_at' => now()
                            ], array_filter([
                                'list_id' => $taskData['list_id'] ?? null,
                                'description' => $taskData['description'] ?? null,
                                'status' => $taskData['status'] ?? null,
                                'due_date' => $taskData['due_date'] ?? null,
                                'start_time' => $taskData['start_time'] ?? null,
                                'end_time' => $taskData['end_time'] ?? null,
                                'pomodoro_required' => $taskData['pomodoro_required'] ?? null,
                                'pomodoro_count' => $taskData['pomodoro_count'] ?? null,
                                'pomodoro_completed' => $taskData['pomodoro_completed'] ?? null,
                                'repeat_type' => $taskData['repeat_type'] ?? null,
                                'notes' => $taskData['notes'] ?? null
                            ], function($value) { return $value !== null; })));

                            \Log::info('TaskController sync: 创建新任务', [
                                'client_id' => $taskData['client_id'],
                                'version' => $taskData['version'] ?? 1
                            ]);
                        } catch (\Illuminate\Database\QueryException $e) {
                            // 如果是重复条目错误，尝试查找并更新现有任务
                            if ($e->getCode() == 23000) { // 完整性约束违反
                                \Log::warning('TaskController sync: 检测到重复client_id，尝试查找现有任务', [
                                    'client_id' => $taskData['client_id'],
                                    'error' => $e->getMessage()
                                ]);
                                
                                // 最后一次尝试查找任务（包括软删除）
                                $task = Task::withTrashed()
                                    ->where('user_id', Auth::id())
                                    ->where('client_id', $taskData['client_id'])
                                    ->first();
                                
                                if ($task) {
                                    // 如果找到了任务，恢复并更新
                                    if ($task->trashed()) {
                                        $task->restore();
                                    }
                                    
                                    $newVersion = ($task->version ?? 1) + 1;
                                    $task->update(array_merge([
                                        'title' => $taskData['title'],
                                        'text' => $taskData['text'],
                                        'completed' => $taskData['completed'] ?? false,
                                        'priority' => $taskData['priority'] ?? 'medium',
                                        'version' => $newVersion,
                                        'last_modified_at' => now()
                                    ], array_filter([
                                        'list_id' => $taskData['list_id'] ?? null,
                                        'description' => $taskData['description'] ?? null,
                                        'status' => $taskData['status'] ?? null,
                                        'due_date' => $taskData['due_date'] ?? null,
                                        'start_time' => $taskData['start_time'] ?? null,
                                        'end_time' => $taskData['end_time'] ?? null,
                                        'pomodoro_required' => $taskData['pomodoro_required'] ?? null,
                                        'pomodoro_count' => $taskData['pomodoro_count'] ?? null,
                                        'pomodoro_completed' => $taskData['pomodoro_completed'] ?? null,
                                        'repeat_type' => $taskData['repeat_type'] ?? null,
                                        'notes' => $taskData['notes'] ?? null
                                    ], function($value) { return $value !== null; })));
                                    
                                    \Log::info('TaskController sync: 重复条目错误后成功更新现有任务', [
                                        'client_id' => $taskData['client_id'],
                                        'new_version' => $newVersion
                                    ]);
                                } else {
                                    \Log::error('TaskController sync: 重复条目错误但无法找到现有任务', [
                                        'client_id' => $taskData['client_id']
                                    ]);
                                    throw $e; // 重新抛出异常
                                }
                            } else {
                                throw $e; // 重新抛出非重复条目的异常
                            }
                        }
                    }
                }
            }

            if ($task) {
                $syncedTasks[] = $task;
            }
        }

        return response()->json([
            'success' => true,
            'data' => $syncedTasks,
            'timestamp' => now()->toISOString()
        ]);
    }
}
